<?php


namespace App\Services;

use Illuminate\Support\Facades\Cache;
use PHPUnit\Util\Exception;
use setasign\Fpdi\Tcpdf\Fpdi;

class CutPdfService extends BaseService
{
    /**
     * 检查 PDF
     */
     public function checkData($partCompanyId, $projectClassifyId, $archivesNo, $pdfPath)
     {
         try {
             $bookTitleInstance   = $this->getBookTitleInstance($partCompanyId, $projectClassifyId);
             $bookCatalogInstance = $this->getBookCatalogInstance($partCompanyId, $projectClassifyId);

             $bookTitleId = $bookTitleInstance->where('archives_no', $archivesNo)->value('id');
             $bookCatalogList = $bookCatalogInstance->where('book_title_id', $bookTitleId)->orderBy('serial_no')->pluck('page_num');

             if ($bookCatalogList->isEmpty()) {
                 throw new Exception('该案卷下面暂无卷内，请导入卷内数据');
             }
             $pdf = new Fpdi();
             $totalPageNum = $pdf->setSourceFile($pdfPath); //该方法的返回值为，PDF总页数
             $maxPageNum = BookCatalogService::getMaxPageNum($partCompanyId, $projectClassifyId, $bookTitleId);
             if ($totalPageNum != $maxPageNum) {
                 throw new Exception("PDF最大页码【{$totalPageNum}】,卷内最大页码【{$maxPageNum}】,请核对！");
             }
             $pageNumArr = $bookCatalogList->toArray(); //页码范围数据
             $data = [];
             foreach ($pageNumArr as $key=>$val) {
                 $serialNo = $key +1;
                 $temp['serial_no'] = "第【{$serialNo}】部分";
                 if (is_numeric($val)) {
                     if (is_numeric($pageNumArr[$key+1])) {
                         if (($pageNumArr[$key+1]-$val) == 1) {
                             $temp['page_scope'] = $val;
                         } else {
                             $temp['page_scope'] = $val.'～'.($pageNumArr[$key+1] - 1);
                         }
                     } else {
                         $pageNum = CommonService::checkPageNum($pageNumArr[$key+1]); // 108～118
                         if ($val == $pageNum['small_page'] - 1) {
                             $temp['page_scope'] = $val;
                         } else {
                             $temp['page_scope'] = $val.'～'.($pageNum['small_page'] - 1);
                         }
                     }
                 } else {
                     $temp['page_scope'] = $val;
                 }
                 if (str_contains($archivesNo, '/')) {
                     $archivesNo = str_replace('/', '-', $archivesNo); //把反斜杠替换为斜杠
                 }
                 $temp['title'] = $archivesNo.'-'.$serialNo;
                 $data[] = $temp;
             }
             $cutPdfKey = self::getCutPdfKey($archivesNo);
             $pdfNumKey = self::getPdfNumKey($archivesNo);
             Cache::put($cutPdfKey, $data, now()->addMinutes(60)); //pdf详细信息
             Cache::put($pdfNumKey, $totalPageNum, now()->addMinutes(60)); //PDF总页码

             return ['msg'=>'', 'data'=>$data];
         }
         catch (Exception $exception){
             return ['msg'=>$exception->getMessage()];
         }
     }

     /**
      * 分割PDF文件
      */
     public function cutPdf($archivesNo, $pdfPath)
     {
         $cutPdfKey  = self::getCutPdfKey($archivesNo);
         $cutPdfList = Cache::get($cutPdfKey);
         $newPdfBasePath = CommonService::createDir("cutPdf/{$archivesNo}");
         foreach ($cutPdfList as $val) {
             $pdf = new Fpdi();
             $page = self::getPageScope($val['page_scope']);
             $totalPageNum = $pdf->setSourceFile($pdfPath); //该方法的返回值为，PDF总页数
             if ($page['end'] > $totalPageNum) break; //如果卷内页号大于待分割的 PDF，多余的不再操作
             for ($pageNo = $page['start']; $pageNo <= $page['end']; $pageNo++) {  //一页一页的读取PDF，添加到新的PDF
                 $templateId = $pdf->importPage($pageNo);  //取出pdf文件的页数
                 $size = $pdf->getTemplateSize($templateId); //获取文件的size 及方向 orientation:L--横向；P--纵向
                 $pdf->AddPage($size['orientation'], $size, true); //添加到新的PDF上
                 $pdf->useTemplate($templateId);
             }
             $newPdfPath = $newPdfBasePath.'/'.$val['title'].'.pdf'; //必须是绝对路径
             $pdf->Output($newPdfPath, "F"); //F在服务器生成pdf; D下载; I在浏览器中打开
             $pdf->Close();
         }
         $downloadUrl = CommonService::createZip("storage/cutPdf/{$archivesNo}");
         $pdfNumKey   = CutPdfService::getPdfNumKey($archivesNo);

         return [
             'download_url' => $downloadUrl,
             'pdf_count'    => Cache::get($pdfNumKey), //PDF总页码
             'cut_pdf_num'  => count($cutPdfList), //分成几份PDF
         ];
     }

    /**
     * 判断文件夹是否存在，不存在则创建
     */
    public static function createDir($dir)
    {
        if (!file_exists($dir)) {
            mkdir($dir);
            chmod($dir, 0777);
        }
        return $dir;
    }

    /**
     * 获取 redis 键名
     */
    public static function getCutPdfKey($archivesNo)
    {
        return $archivesNo.':pdf-info';
    }

    /**
     * 获取 redis 键名
     */
    public static function getPdfNumKey($archivesNo)
    {
        return $archivesNo.':pdf-num';
    }

    /**
     * 把 page_scope 分解
     */
    public static function getPageScope($pageNum)
    {
        if (is_numeric($pageNum)) {
            $smallPage = $pageNum;
            $bigPage   = $pageNum;
        } else {
            $pos = strpos($pageNum, '～');
            $smallPage = mb_substr($pageNum, 0, $pos);
            $result = json_encode(mb_substr($pageNum, $pos + 1));
            if (!empty($result)) {
                $bigPage = mb_substr($pageNum, $pos + 1);
            } else {
                $bigPage = mb_substr($pageNum, $pos + 3);
            }
        }
        return [
            'start' => (int)$smallPage,
            'end'   => (int)$bigPage
        ];
    }


}
